package cn.genmer.test.security.controller;

import cn.genmer.test.security.annotation.LoginRequired;
import cn.genmer.test.security.model.CustomUser;
import cn.genmer.test.security.model.User;
import cn.genmer.test.security.model.dto.ModifiedSource;
import cn.genmer.test.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/findall")
    public String findAll(){
        return "userInfo";
    }

    @GetMapping("/index")
    public String index(){
        return "欢迎来到首页！";
    }
    @LoginRequired
    @GetMapping("/admin")
    public String admin(){
        return "admin";
    }

    @GetMapping("/role")
    public String role(){
        return "role";
    }

    @GetMapping("/common")
    public String common(){
        return "common";
    }

    @GetMapping("/logtest")
    public String logTest(){
        userService.updateUserInfo(new User(1L,"李四","19"), new ModifiedSource("1000"));

        return "ok";
    }

    @LoginRequired
    @GetMapping("/manager")
    public String manager(){
        return "manager";
    }

    @PostMapping("/add")
    @Secured({"ROLE_manager","Role_common"})
    @PreFilter(value = "filterObject.id%2 == 0")
    public String add(@RequestBody List<CustomUser> users){
        if (users == null && users.size() <= 0){
            return "参数为空或者列表长度为0";
        }
        for (Object o: users){
            Map map = (Map) o;
            String id = (String) map.get("id");
            System.out.println(id);
        }
        System.out.println("添加成功");
        return "添加成功！";
    }

    @GetMapping("/delete")
//    @Secured({"ROLE_delete","Role_common"})
    @PreAuthorize("hasAnyAuthority('admin')")
//    @PostAuthorize("hasAnyAuthority('admins')")
    @PostFilter("filterObject.id == '0'")
    public ArrayList<CustomUser> delete(){
        ArrayList<CustomUser> customUsers = new ArrayList<>();
        customUsers.add(new CustomUser("0", "小米", "123"));
        customUsers.add(new CustomUser("01", "小h", "123"));
        return customUsers;
    }
}
